<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/7
 * Time: 9:56
 */

namespace app\index\controller;
header("Content-type: text/html; charset=utf-8");

use app\common\controller\PayBase;
use think\Db;
use app\index\model\ChongzhiList;
use think\Exception;

class Paymjzf extends PayBase{
    private $merchNo;
    private $key;
    private $pay_url;
    private $back_url;
    private $view_url;
    private $version;

    public function __construct(){
        parent::__construct();
        $this->merchNo = 'MJF201806150617';
        $this->key = '065D09A328DC9F828B1F0819062F5897';
        $this->pay_url = [
            'ZFB' => 'http://zfb.mjzfpay.com:90/api/pay',
            'ZFB_WAP'=>'http://zfbwap.mjzfpay.com:90/api/pay',
            'WX' => 'http://wx.mjzfpay.com:90/api/pay',
            'WX_WAP' => 'http://wxwap.mjzfpay.com:90/api/pay',
            'QQ' => 'http://qq.mjzfpay.com:90/api/pay',
            'QQ_WAP' => 'http://qqwap.mjzfpay.com:90/api/pay',
            'JD' => 'http://jd.mjzfpay.com:90/api/pay',
            'JD_WAP' => 'http://jdwap.mjzfpay.com:90/api/pay',
            'BAIDU' => '',
            'UNION_WALLET' => 'http://union.mjzfpay.com:90/api/pay',
            'MBANK' => 'http://mbank.mjzfpay.com:90/api/pay',
            'ZFB_AUTH_CODE' => 'http://zfb.mjzfpay.com:90/api/pay',
            'ZFB_AUTH_CODE_WAP' => 'http://zfbwap.mjzfpay.com:90/api/pay',
            'WX_AUTH_CODE' => 'http://wx.mjzfpay.com:90/api/pay',
            'WX_AUTH_CODE_WAP' => 'http://wxwap.mjzfpay.com:90/api/pay',
            'ZFB_B' => 'http://zfb.mjzfpay.com:90/api/pay',
            'ZFB_WAP_B'=>'http://zfbwap.mjzfpay.com:90/api/pay',
            'WX_B' => 'http://wx.mjzfpay.com:90/api/pay',
            'WX_WAP_B'=>'http://wxwap.mjzfpay.com:90/api/pay',
            'WX_H5' => 'http://wxwap.mjzfpay.com:90/api/pay'
        ];
        $this->back_url = 'http://www.my67.cc/index/Paymjzf/callBack';
        $this->view_url = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/index/Paymjzf/viewUrl';
        $this->version = 'V3.0.0.0';

    }
    public function initPay($username='',$pay_type='',$amount=-1,$from=0){
        //接收数据
        $user = cookie('username','');
        $password = cookie('password','');
        $username =  empty($username) ? input('post.username','') : $username;
        $pay_type = empty($pay_type) ? input('post.pay_type','') : $pay_type;
        $amount = -1==$amount ? input('post.amount',0) : $amount;
        $ctime = time();

        if($pay_type=='null' || $pay_type=='') return packJson('',$pay_type.'请选择支付方式',500);
        $pay_method = Db::name('pay_type_list')
            ->alias("a")
            ->join('__PAY_METHOD__ b','a.method_id=b.id','LEFT')
            ->where(['a.method'=>17,'a.type_value'=>$pay_type])
            ->field('a.type_name,b.name,b.id,b.method,b.money')->find();

        $remark = $pay_method['type_name'].'-'.$pay_method['name'];

        //验证用户信息
        if( 0==$from ){
            if(!$user || !$username || ($user!=$username)) return packJson('','用户身份验证失败',500);
            $user_info = Db::name('username')->field('id,us_class,swzh,nbzh')->where(['username'=>$username,'password'=>$password])->find();
        }else{
            $user_info = Db::name('username')->field('id,us_class,swzh,nbzh')->where(['username'=>$username])->find();
        }
        if(!$user_info) return packJson('','用户身份验证失败',500);
        if($user_info['swzh'] == 1) return packJson('','试玩账号无法充值',500);
        if($user_info['nbzh'] == 1) return packJson('','内部账号不支持线上充值',500);

        //充值防骚扰是否开启，并进行处理
        $harassment = Db::name('xt_czfsr')->find();
        if($harassment['open'] > 0) {
            $nowys = $ctime - $harassment['time_xs'] * 60;
            $old_czjl = Db::name('chongzhi_list')->where('username',$username)->where('cztime','>',$nowys)->find();
            if($old_czjl['id'] > 0) {
//                return packJson('',"系统充值防骚扰已开启，{$harassment['time_xs']}分钟内只能充值1次！",500);
            }
        }
        //生成订单号
        $order_sn = 'MJF' . str_pad($user_info['id'],5,'0',STR_PAD_LEFT) . $ctime . rand(111,999);
        //组装数据
        if( 1==$from ) $this->view_url.="Third";
        $data = array();

        $data['orderNum'] = $order_sn;
        $data['version'] = $this->version;
        $data['charset'] = 'UTF-8';
        $data['randomNum'] = (string) rand(1000,9999);
        $data['merchNo'] = $this->merchNo;
        $data['netwayCode'] = $pay_type;   	//WX:微信支付,ZFB:支付宝支付
        $data['amount'] = strval( floatval($amount) * 100 );	// 单位:分
        $data['goodsName'] = '明捷线上支付';
        $data['callBackUrl'] = $this->back_url;
        $data['callBackViewUrl'] = $this->view_url;
        $data['sign'] = create_sign($data,$this->key);

        $json = json_encode_ex($data);
        $Rsa = new Rsa();
        $dataStr = $Rsa->encode_pay($json);
        $param = 'data=' . urlencode($dataStr) . '&merchNo=' . $this->merchNo . '&version=' . $this->version;

        $result = wx_post($this->pay_url[$pay_type],$param);
        $rows = json_to_array($result,$this->key);

        if( '00' === $rows['stateCode'] ){
            $u = Db::name('username')->where('username',$username)->value('je');
            $model = new ChongzhiList();
            if($model->setTransRechargeInfo($order_sn,$amount,$username,0,0,1,$remark,$ctime,'明捷线上支付','系统自动',get_ip(),0,$pay_type,0,0,0,0,$user_info['us_class'],'',0,0,$u)){
                //跳转支付页
                return packJson($rows['qrcodeUrl'],'',200);
            }else{
                return packJson('',"订单生产错误",500);
            }
        }else{
            return packJson('',$rows['msg'],500);
        }
    }
    public function callBack(){
        file_put_contents('mj_back.txt',var_export(input(),true),FILE_APPEND);

//        $sign = input('sign','');
//        $ordernumber = input('oid','');
//        $orderstatus = input('status',0);
//        $paymoney = input('m',0);
//        $sysnumber = input('oidPay','');
//        $attach = input('uid','');
//
//        $sign_str = $ordernumber.'&'.$orderstatus.'&'.$paymoney.'&'.$this->key;
//        if (md5($sign_str) == $sign && 1==intval($orderstatus)) {
//
//            $order_info = Db::name('chongzhi_list')->where('ddbh',$ordernumber)->find();
//            $user_info = Db::name('username')->where('username',$order_info['username'])->find();
//
//            Db::startTrans();
//            try {
//                if( 1==intval($order_info['zt']) ){
//                    throw new Exception("该订单已经成功通知");
//                }
//                //计算优惠金额
//                $msje = $msbs = 0;
//                $cz_set = Db::name('xt_chongzhi')->find();
//                $user_class = Db::name('us_class')->where('id',$user_info['us_class'])->find();
//                $zsje = $paymoney * $user_class['czzsbl'] / 100;
//                $zsbs = $user_class['czzsbl'];
//                if($paymoney >= $cz_set['xscz_je']) {
//                    $msje = $paymoney * $cz_set['xscz_zs'] / 100;
//                    $msbs = $cz_set['xscz_zs'];
//                }
//                //充值方案赠送
//                $pay_method = Db::name('pay_type_list')
//                    ->alias("a")
//                    ->join('__PAY_METHOD__ b','a.method_id=b.id','LEFT')
//                    ->where(['a.method'=>13,'a.type_value'=>trim($order_info['liuyan'])])
//                    ->field('a.type_name,b.name,b.id,b.method,b.money')->find();
//                $method_money = 0.00;
//                if( floatval( $pay_method['money'] ) > 0 ){
//                    if( 0==intval( $pay_method['method'] ) ){
//                        //金额
//                        $method_money = $pay_method['money'];
//                    }else{
//                        //比例
//                        $method_money = floatval($paymoney) * floatval($pay_method['money']) / 100;
//                    }
//                }
//                $method_money = sprintf("%.2f",substr(sprintf("%.3f", $method_money), 0, -2));
//                if( !Db::name('chongzhi_list')->where(['id'=>$order_info['id']])->update(['je'=>$paymoney,'hy_zsje'=>$zsje,'hy_zsbs'=>$zsbs,'hy_msje'=>$msje,'hy_msbs'=>$msbs,'method_money'=>$method_money]) ){
//                    throw new Exception("更新订单信息金额错误");
//                }
//
//                $dml_set = Db::name('xt_dmsz')->where('id',1)->find();
//                if( 1==$cz_set['dmopen'] ){
//                    $dmls = (floatval($msje) + floatval($zsje) + floatval($paymoney)+ floatval($method_money)) * $dml_set['xscz_dmbs'];
//                }else{
//                    $dmls = floatval($paymoney) * $dml_set['xscz_dmbs'];
//                }
//                //充值后账户总金额
//                $czhje = floatval($msje) + floatval($zsje) + floatval($paymoney)+ floatval($method_money) + floatval($user_info['je']);
//                //充值总金额
//                $czzje = floatval($paymoney) + floatval($user_info['czzje']);
//                //用户当前打码量
//                $dml = $user_info['dml'] + $dmls;
//
//                if( !model('ChongzhiList')->updateRechargeInfo($ordernumber,$sysnumber,1,$czhje,time()) ){
//                    throw new Exception("更新订单信息错误");
//                }
//                if( !model('Username')->upUserXsczInfo($czhje,$dml,$czzje,$order_info['username']) ){
//                    throw new Exception("更新用户金额错误");
//                }
//                Db::name('username')->where('username',$order_info['username'])->setInc('cz_num');
//
//                $fav_money = floatval($msje)+floatval($zsje)+ floatval($method_money);
//                //满送金额，等级赠送金额，充值方案赠送金额
//                $extcj = array(
//                    'username'=>$user_info['username'],
//                    'user_class'=>$user_info['us_class'],
//                    'fstime'=>time(),
//                    'czadmin' => '系统赠送',
//                );
//                $cjhje = floatval($paymoney) + floatval($user_info['je']) + floatval($msje);
//
//                if( floatval($msje) > 0 ){
//                    $extcj['beizhu'] = '系统赠送，充值满送金额';
//                    $extcj['cjje'] = $msje;
//                    $extcj['cjhje'] = $cjhje;
//                    Db::name('caijin_list')->insert($extcj);
//                }
//                $cjhje += floatval($zsje);
//                if( floatval($zsje) > 0 ){
//                    $extcj['beizhu'] = '系统赠送，充值等级赠送金额';
//                    $extcj['cjje'] = $zsje;
//                    $extcj['cjhje'] = $cjhje;
//                    Db::name('caijin_list')->insert($extcj);
//                }
//                $cjhje += floatval($method_money);
//                if( floatval($method_money) > 0 ){
//                    $extcj['beizhu'] = '系统赠送，充值方案赠送金额';
//                    $extcj['cjje'] = $method_money;
//                    $extcj['cjhje'] = $cjhje;
//                    Db::name('caijin_list')->insert($extcj);
//                }
//
//                $data = array('username' =>$order_info['username'],'test'=>"您账户充值金额：{$paymoney}，赠送金额：{$fav_money}。已充值到账，请注意查收！",'xx_time'=>time(),'ifdq'=>0);
//                Db::name('xiaoxi')->data($data)->insert();
//                Db::commit();
//                header('HTTP/1.1 200 OK');exit;
//            } catch (\Exception $e) {
//                Db::rollback();
//                header('HTTP/1.1 400 Bad Request');
//                exit;
//            }
//        }
//        header('HTTP/1.1 400 Bad Request');
    }
    public function viewUrl(){
        file_put_contents('mj_view.txt',var_export(input(),true),FILE_APPEND);
    }
    public function viewUrlThird(){
        file_put_contents('mj_view_three.txt',var_export(input(),true),FILE_APPEND);
    }
}

class Rsa{
    private $pay_public_key;
    private $remit_public_key;
    private $private_key;

    public function __construct($key = null){
        $data['private_key'] = 'MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBALChwD0oQvO4XnFx/Qq9Mk4DbOKvDptrejNBWiLdDUTQ4QC+22A8odlKyUjD1fDaGkEhW4A4sDeRuPEpdn3wB+nQ/yQQfpoyvmyTXptFAh+bUJFCHD6J3QEImkPws5rwe3qme0Bk9rsjck5jPcUdFlScqfKPPlPOEaNEv3ZFof+HAgMBAAECgYBo8kJBVBmrq4DZ0MtzRQSNm7VnXnHEYHCD4bGHg2Wt3JnDkqLPpFbZv3im9ky4RS5SQlqWbZgt/DQxfdw8aZCZGZXWH7pYa9+AXs0+e0ose6i50Fe8ta6n8HN+8GPf0Vl+Im4mSFocsQ+zJ6YEkedHAk9zUv9jEMyhTexH20iwyQJBAPdAYDEu9BlEFJUM5ukTWUVxjQ8tctFzzcS+s/wcQeQ5Asazcx7lv7+5FAS4irjeekdW3Mcn8XNN1zSrMKx9E8MCQQC24bJeGgVE1iPovpt8FW8CS9NxX2h4fgslwC1tBaNsJR+jyz38/UxJRbA2eYY1Mv0Hb04EFKKPC91nA9gLpzztAkALyTHMpmRUX/5rLHZFXfq/aK5ErvHuMgr4+e4yclZhvqX3Os6eBm2hgf0GTJWwQkqp4+YaSDkmOeusQwzK7BtpAkAtGafFMSGPgkfExAzQIvEHXe+9C8xVuq/BFY2eTz+oEdelqx+UXlsLztXP+VQxlmt0A+z3cKdOI5zsJLSI2ytZAkBv6s/zEPMReqVi4HjSWF6xia8NRrDB1TLWyojJqWKAQ6M+cv0Tne1UDTTA+GgklKVdhNMJwGtIKXLlIt5eGhIx';
        $data['pay_public_key'] = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCQvHsd32S+8j7N+VF3g7SthcYNOd4TB/DO1Krs1cAVl/cydFYlZdTZ009WoW60vu3miLvu7UZnY5dhl2eFoTNFUbZjhyubl64gXCeJRE46cDVBQauwlErpV5Zwha/SwbaG/vZ9CXLOneM9/GWooix8+GWZsrelrwJ7yQerE9NpuwIDAQAB';
        $data['remit_public_key'] = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCNHBBInSAiToNWqiUL98/uEkUS52o+42qfnYD2FxMtrKZfNfmR0B/5GZya0mG0RPX56HTrNO4kIZVAJWIll08BGXrSdY+uVPBoe9TErqf8pFfo9gI64xH6fNfrZ1vQrmywHSzbgXqeOBvIwxijCXYdS90hhDux478Uj+ZCjDIpWwIDAQAB';
        $this->private_key = "-----BEGIN RSA PRIVATE KEY-----\r\n";
        foreach (str_split($data['private_key'],64) as $str){
            $this->private_key = $this->private_key . $str . "\r\n";
        }
        $this->private_key = $this->private_key . "-----END RSA PRIVATE KEY-----";

        $this->pay_public_key = "-----BEGIN PUBLIC KEY-----\r\n";
        foreach (str_split($data['pay_public_key'],64) as $str){
            $this->pay_public_key = $this->pay_public_key . $str . "\r\n";
        }
        $this->pay_public_key = $this->pay_public_key . "-----END PUBLIC KEY-----";



        $this->remit_public_key = "-----BEGIN PUBLIC KEY-----\r\n";
        foreach (str_split($data['remit_public_key'],64) as $str){
            $this->remit_public_key = $this->remit_public_key . $str . "\r\n";
        }
        $this->remit_public_key = $this->remit_public_key . "-----END PUBLIC KEY-----";
    }

    public function encode_pay($data){#加密
        $pu_key = openssl_pkey_get_public($this->pay_public_key);
        if ($pu_key == false){
            echo "打开密钥出错";
            die;
        }
        $encryptData = '';
        $crypto = '';
        foreach (str_split($data, 117) as $chunk) {
            openssl_public_encrypt($chunk, $encryptData, $pu_key);
            $crypto = $crypto . $encryptData;
        }

        $crypto = base64_encode($crypto);
        return $crypto;

    }


    public function encode_remit($data){#加密
        $pu_key = openssl_pkey_get_public($this->remit_public_key);
        if ($pu_key == false){
            echo "打开密钥出错";
            die;
        }
        $encryptData = '';
        $crypto = '';
        foreach (str_split($data, 117) as $chunk) {
            openssl_public_encrypt($chunk, $encryptData, $pu_key);
            $crypto = $crypto . $encryptData;
        }

        $crypto = base64_encode($crypto);
        return $crypto;

    }



    public function decode($data){
        $pr_key = openssl_get_privatekey($this->private_key);
        if ($pr_key == false){
            echo "打开密钥出错";
            die;
        }
        $data = base64_decode($data);
        $crypto = '';
        foreach (str_split($data, 128) as $chunk) {
            openssl_private_decrypt($chunk, $decryptData, $pr_key);
            $crypto .= $decryptData;
        }
        return $crypto;
    }


}


function p($array){
    $str = '<pre>' . print_r($array,true) . '</pre>';
    echo $str;
}
function ps($array){
    $str =  print_r($array,true);
    return $str;
}

function wx_post($url,$data){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $tmpInfo = curl_exec($ch);
    if (curl_errno($ch)) {
        return curl_error($ch);
    }
    return $tmpInfo;

}

function json_encode_ex($value){
    if (version_compare(PHP_VERSION,'5.4.0','<')){
        $str = json_encode($value);
        $str = preg_replace_callback("#\\\u([0-9a-f]{4})#i","replace_unicode_escape_sequence",$str);
        $str = stripslashes($str);
        return $str;
    }else{
        return json_encode($value,320);
    }
}

function json_decode_ex($value){
    return json_decode($value,true);
}

function replace_unicode_escape_sequence($match) {
    return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE');
}
function log_write($log){
    $file = date('Y-m-d') . '.log';
    $str = date('H:i:s') . " " . $log . "\r\n";
    file_put_contents($file,$str,FILE_APPEND);
}

function create_sign($data,$key){
    ksort($data);
    $sign = strtoupper(md5(json_encode_ex($data) . $key));
    return $sign;
}

function json_to_array($json,$key){
    $array = json_decode_ex($json);
    if ($array['stateCode'] == '00'){
        $sign_string = $array['sign'];
        ksort($array);
        $sign_array = array();
        foreach ($array as $k => $v) {
            if ($k !== 'sign'){
                $sign_array[$k] = $v;
            }
        }

        $md5 =  strtoupper(md5(json_encode_ex($sign_array) . $key));
        if ($md5 == $sign_string){
            return $sign_array;
        }else{
            $result = array();
            $result['stateCode'] = '99';
            $result['msg'] = '返回签名验证失败';
            return $result;
        }



    }else{
        $result = array();
        $result['stateCode'] = $array['stateCode'];
        $result['msg'] = $array['msg'];
        return $result;
    }

}


function callback_to_array($json,$key){
    $array = json_decode_ex($json);
    $sign_string = $array['sign'];
    ksort($array);
    $sign_array = array();
    foreach ($array as $k => $v) {
        if ($k !== 'sign'){
            $sign_array[$k] = $v;
        }
    }

    $md5 =  strtoupper(md5(json_encode_ex($sign_array) . $key));
    if ($md5 == $sign_string){
        return $sign_array;
    }else{
        $result = array();
        $result['payStateCode'] = '99';
        $result['msg'] = '返回签名验证失败';
        return $result;
    }

}